package com.xxcxcxcx.jobsystem.common.capability;

import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityProvider;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.util.INBTSerializable;
import net.minecraftforge.common.util.LazyOptional;
import org.jetbrains.annotations.NotNull;

import javax.annotation.Nullable;

public class JobCapabilityProvider extends CapabilityProvider<JobCapabilityProvider> implements INBTSerializable<CompoundTag> {
    public static final Capability<JobCapability> CAPABILITY = CapabilityManager.get(new CapabilityToken<>(){});

    private final LazyOptional<JobCapability> capability;

    public JobCapabilityProvider(Player player) {
        super(JobCapabilityProvider.class);
        capability = LazyOptional.of(() -> new JobCapability(player));
    }

    @Override
    public CompoundTag serializeNBT() {
        return capability.resolve().isPresent() ? capability.resolve().get().serializeNBT() : new CompoundTag();
    }

    @Override
    public void deserializeNBT(CompoundTag nbt) {
        capability.ifPresent(cap -> cap.deserializeNBT(nbt));
    }

    @NotNull
    @Override
    public <T> LazyOptional<T> getCapability(@NotNull Capability<T> cap, @Nullable Direction side) {
        return CAPABILITY.orEmpty(cap, capability);
    }

    public static LazyOptional<JobCapability> getPlayerData(Player player) {
        if(player == null) {
            return LazyOptional.empty();
        }
        return player.getCapability(JobCapabilityProvider.CAPABILITY);
    }
}
